<script setup lang='ts'>
  import { reactive, computed, watch } from 'vue';
  import { productTypeArr, goodsClass } from '@/pinia/getter';
  import { propApi } from '@/api/controller'
  import { ToastWarning } from '@/utils/public';
  import Pagination from "../Pagination/index.vue";
  import xmImage from '../xmImage/index.vue';
  const props = defineProps({
    goods_id:{
      type:[Number,String],
      default:''
    },
    goods_type:{
      type:[Number,String],
      default:0
    },
    version:{
      type:String,
      default:'0.0.0'
    },
    show_goods_type:{
      type:Array<Number|String>,
      default:()=>[]
    },
  })
  // watch(props,()=>{
  //   if(props.goods_id) action.goods_id = props.goods_id
  // })
  let old_goods_id = 0 as string | number
  const goods_id = computed({
    set(val) {
      return val
    },
    get() {
      let getListSet = false
      if(props.goods_id  && action.list.length == 0 && !action.getState) {
        getListSet = true
      }
      if(old_goods_id != props.goods_id) {
        getListSet = true
      }
      if(getListSet) {
        old_goods_id = props.goods_id
        if(props.version == '0.0.0') {
          getGiftList()
        }
        if(props.version == '0.0.1') {
          openSerachGoods(false)
        }
      }
      return props.goods_id
    }
  })
  const $emit = defineEmits(['update:goods_id','update:goods_info','update:goods_image','update:goods_type'])
  const action = reactive({
    loading:false,
    getState:false,
    // goods_id:'' as number | string,
    options:[] as Array<any>,
    list:[] as Array<any>,
    dialogFormVisible:false,
    goodsClassifyList:[] as Array<any>,
    goods_name:'',
    total:0,
  })
  const initialQuery = {
    page: 1,
    limit: 10,
    goods_type: 0 as number | string,
    sort: "+id",
    gift_id: "" as number | string,
    gift_name: "",
    mall_goods_class: -1,
    level: null,
  }
  const listQuery = reactive({
    ...initialQuery
  })
  const remoteMethod = async(query:any='')=>{
    if(query.length >= 1 && action.options.length == 0) {
      await getGiftList()
    }
    if(action.list.length > 0) {
      if(query.length >= 1) {
        const list = action.options.filter((item) => {
          return item.goods_name.toLowerCase().includes(query.toLowerCase())
        })
        action.options = list
      } else {
        action.options = action.list
      }
    }
  }
  const getGiftList = async()=>{
    action.loading = true
    const res = await propApi.getGoods({
      page:1,
      limit:99999,
      goods_type:props.goods_type,
      mall_goods_class:-1,
    })
    action.loading = false
    const { data=[] } = res.data
    action.options = data
    action.list = data
  }
  // table表格选中商品
  const handleSelected = (row:any = {})=>{
    const { big_img='', goods_id:id } = row
    if(!id) return ToastWarning('缺少商品ID')
    emitQuery(id,row,big_img)
  }
  const openSerachGoods = async(show:Boolean = true)=>{
    action.goodsClassifyList = productTypeArr.filter(res=>{
      const { value='' } = res
      if(props.show_goods_type.indexOf(value) > -1) return res
    })
    const { goods_id, goods_type } = props
    if(goods_type) {
      listQuery.goods_type = goods_type
    }
    if(goods_id) {
      listQuery.gift_id = goods_id
      await newGetList()
      const name = action.list.find(res=>res.goods_id == goods_id)?.goods_name || { goods_name:'' }
      action.goods_name = name
    } else {
      listQuery.gift_id = ''
      action.list = []
    }
    if(show) action.dialogFormVisible = true
  }
  const newGetList = async()=>{
    const res = await propApi.getGoods(listQuery)
    action.loading = false
    const { data=[], total } = res.data
    if(total == 0) action.getState = true
    action.total = total
    action.list = data
  }
  const handleSerach = () => {
    listQuery.page = 1;
    newGetList();
  };
  const selectChange = (goods_id:any='')=>{
    if(goods_id == 'clear') {
      emitQuery('',{goods_id:0,goods_name:''},'')
      return
    }
    if(goods_id) {
      const obj = action.options.find(res=>res.goods_id == goods_id)
      const { goods_id:id='', goods_name:name='', big_img='' } = obj
      emitQuery(goods_id,obj,big_img)
    }
  }
  /**
   * 
   * @param id 商品id
   * @param gift_info 商品详情 
   * @param image 商品图片
   */
   const emitQuery = (id:number | string = '', goods_info:any = {}, image:string = '' )=>{
    const { goods_name='', goods_type=0 } = goods_info
    $emit('update:goods_id',id)
    $emit('update:goods_info',goods_info)
    $emit('update:goods_image',image)
    $emit('update:goods_type',goods_type)
    action.goods_name = goods_name
    if(action.dialogFormVisible) {
      action.total = 0
      action.list = []
      Object.assign(listQuery,{...initialQuery})
      action.getState = false
      action.dialogFormVisible = false
    }
  }
  const goodsTypeFilters = (type:number = -1)=>{
    const { label='其他' } = productTypeArr.find(res=>res.value == type) || { label:'其他' }
    return label
  }
</script>

<template>
  <el-select
    v-if="version == '0.0.0'"
    v-model="goods_id"
    filterable
    remote
    placeholder="请选择商品"
    clearable
    :remote-method="remoteMethod"
    :loading="action.loading"
    @change="selectChange"
    @clear="selectChange('clear')">
    <el-option
      :label="item.goods_name"
      :value="item.goods_id"
      v-for="(item, index) in action.options"
      :key="item.goods_id"/>
  </el-select>
  <div v-if="version == '0.0.1'">
    <el-button v-if="!goods_id" type="primary" @click="openSerachGoods()">搜索商品</el-button>
    <el-tag v-if="goods_id" size="large">
      <span style="font-size: 14px;">商品ID：{{goods_id}} 商品名称：{{ action.goods_name }}</span>
      <span class="pointer xm-ml10" style="color:blue; font-size: 14px;" @click="openSerachGoods()">重新选择</span>
    </el-tag>
    <el-dialog
    top="10vh"
    class="xm-dialog serachGiftBox"
    v-model="action.dialogFormVisible"
    width="60%">
    <div class="xm-headTab">
      <div class="labelBox">
        <div class="labelItem">
          <div class="label">商品ID：</div>
          <el-input :validate-event="false" v-model="listQuery.gift_id" placeholder="请输入商品ID"/>
        </div>
        <div class="labelItem">
          <div class="label">商品名称：</div>
          <el-input :validate-event="false" v-model="listQuery.gift_name" placeholder="请输入商品名称"/>
        </div>
        <div class="labelItem">
          <div class="label">商品类型：</div>
          <el-select :validate-event="false" v-model="listQuery.goods_type" placeholder="请选择商品类型">
            <el-option
              v-for="item in action.goodsClassifyList"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="labelItem">
          <div class="label">商品分类：</div>
          <el-select :validate-event="false" v-model="listQuery.mall_goods_class" placeholder="请选择商品分类">
            <el-option label="全部分类" :value="-1" />
            <el-option
              v-for="item in goodsClass"
              :label="item.label"
              :value="item.value" />
          </el-select>
        </div>
        <div class="labelItem">
          <el-button type="primary" @click="handleSerach">查询</el-button>
        </div>
      </div>
    </div>
    <el-table
      class="xm-main xm-TableCenter"
      :data="action.list"
      border
    >
      <el-table-column width="100" prop="goods_id" label="商品ID" />
      <el-table-column width="180" prop="goods_name" label="商品名称" />
      <el-table-column width="120" prop="goods_type" label="商品类型">
        <template #default="scoped">
          {{ goodsTypeFilters(scoped.row.goods_type) }}
        </template>
      </el-table-column>
      <el-table-column width="120" prop="mall_goods_class" label="商品分类">
        <template #default="scoped">
          {{ goodsClass.find(res=>res.value == scoped.row.mall_goods_class)?.label || ''  }}
        </template>
      </el-table-column>
      <el-table-column width="140" prop="big_img" label="商品图片">
        <template #default="scoped">
          <xmImage :src="scoped.row.big_img" :list="[scoped.row.big_img]" />
        </template>
      </el-table-column>
      <el-table-column width="100" prop="is_show" label="是否显示">
        <template #default="scoped">
          <div>
            <el-icon>
              <SuccessFilled v-if="scoped.row.is_show == 1" style="color: #67C23A;" />
              <CircleCloseFilled v-if="scoped.row.is_show == 0" style="clear: #F56C6C;" />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="110" sortable prop="sort" label="商品排序" />
      <el-table-column min-width="340" prop="price" label="价格" >
        <template #default="scoped">
          <div
              v-for="(item, key) in scoped.row.mall_goods_sku"
              :key="key">
            <el-tag>
              {{ item.time_limit }}天 {{ item.price }}钻石
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="200" show-overflow-tooltip prop="goods_desc" label="商品描述" />
      <el-table-column width="140" fixed="right" label="操作">
        <template #default="scoped">
          <el-button v-if="goods_id != scoped.row.gift_id" type="primary" @click="handleSelected(scoped.row)">选择商品</el-button>
          <el-button v-else type="danger" @click="selectChange('clear')">取消选中</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-show="action.total > 0" :total="action.total" v-model:page="listQuery.page"
      v-model:limit="listQuery.limit" @pagination="getGiftList" />
    </el-dialog>
  </div>
</template>